package com.heartech.prediciton_wx.controller.material;

import com.heartech.prediciton_wx.service.media.MediaService;
import com.heartech.prediciton_wx.utils.token.AccessTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@RestController
@RequestMapping("/wxpublic")
public class UpdateMaterialController {

    @Autowired
    private  MediaService mediaService;

    @PostMapping("/media_upload")
    public void mediaUpload() {
        String accessToken = AccessTokenUtil.getAccessToken();

        if (accessToken != null) {
            String mediaType = "image";
            String relativeImagePath = "imgs/HearTech.jpg";

            try {
                uploadMediaFile(accessToken, mediaType, relativeImagePath);
            } catch (IOException e) {
                log.error("Error uploading media file", e);
            }
        } else {
            log.error("Failed to get access_token");
        }
    }


    private String uploadMediaFile(String accessToken, String mediaType, String relativePath) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + mediaType;

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 允许输出流
        con.setDoOutput(true);

        // 根据当前工作目录构建图片的绝对路径
        String workingDir = System.getProperty("user.dir");
        String filePath = workingDir + File.separator + relativePath;

        File file = new File(filePath);
        if (!file.exists()) {
            log.error("File not found: " + filePath);
            return "File not found";
        }

        // 设置边界字符串
        String boundary = "--------------------------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream os = con.getOutputStream()) {
            // 构建表单数据
            String lineSeparator = "\r\n";

            // 添加文件部分
            os.write(("--" + boundary + lineSeparator).getBytes());
            os.write(("Content-Disposition: form-data; name=\"media\"; filename=\"" + file.getName() + "\"" + lineSeparator).getBytes());
            os.write(("Content-Type: application/octet-stream" + lineSeparator + lineSeparator).getBytes());

            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }

            // 添加表单结束标识
            os.write((lineSeparator + "--" + boundary + "--" + lineSeparator).getBytes());
            os.flush();
        }

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            log.info("Media Upload Response :: " + response.toString());

            try {
                JSONObject jsonResponse = new JSONObject(response.toString());
                String obtainedMediaId = jsonResponse.getString("media_id");
                mediaService.setMediaId(obtainedMediaId);
                log.info(mediaService.getMediaId());
                return obtainedMediaId;  // 直接返回 obtainedMediaId
            } catch (JSONException e) {
                log.error("Error parsing media_id from response", e);
                return "Error parsing JSON";
            }
        } else {
            log.error("Media Upload request not worked");
            return "HTTP error code: " + responseCode;
        }

    }

}
